package services

import (
	"demo/core"
	"demo/help"
	"demo/models"
	"demo/response/data"
	"errors"
	"fmt"
)

type User struct {
	UserName string `form:"user_name" json:"user_name" binding:"required,min=3,max=15" example:"liyanjun"`
	Password string `form:"password" json:"password" binding:"required,min=6,max=20" example:"123456"`
}

func (u *User) Register() bool {
	user := models.User{}
	var count int
	core.Db.Where("user_name=?", u.UserName).First(&user).Count(&count)
	if count > 0 {
		return false
	}
	user.UserName = u.UserName
	hash, err := help.GeneratePassword(u.Password)
	if err != nil {
		return false
	}
	user.Password = hash
	err = core.Db.Create(&user).Error
	if err != nil {
		return false
	}
	return true
}

func (u *User) Login() (data.Login, error) {
	var result data.Login
	user := models.User{}
	err := core.Db.Where("user_name=?", u.UserName).Select("id,user_name,password,created_at").First(&user).Error
	if err != nil {
		return result, errors.New("用户不存在")
	}
	res := help.CheckPassword(user.Password, u.Password)
	if !res {
		return result, errors.New("密码错误")
	}
	result = data.BindLogin(user)
	token, err := help.GenerateToken(user.ID, user.UserName)
	if err != nil {
		fmt.Println(err.Error())
		return result, errors.New("生成token失败")
	}
	result.Token = token
	// fmt.Println(token)
	//解析token
	// claims, err := help.ParseToken(token)
	// if err == nil {
	// fmt.Println(claims.Id, claims.UserName)
	// }
	return result, nil
}
